/**
 * 
 */
package com.heer.RD.projecthour.page;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;

import com.heer.RD.projecthour.component.DeptProjMultiChoice;
import com.heer.RD.projecthour.component.UserProjCostPanel;
import com.heer.RD.util.UtilsMisc;
import com.heer.joss.persistence.convention.ExpressionUtil;


/**
 * @author ZhaoZehui
 *
 */
public class ProjectStatPage extends BasePage {

	/**
	 * 
	 */
	public ProjectStatPage(PageParameters para) {
		
		String currDateStr = UtilsMisc.getCurrDateStr();
	
		final List<Map> projStatList = new ArrayList();
		
		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
		
		final TextField beginDate = new TextField("beginDate", new Model<String>(""));
		beginDate.setMarkupId("beginDate").setOutputMarkupId(true);
		final TextField endDate = new TextField("endDate", new Model<String>(currDateStr));
		endDate.setMarkupId("endDate").setOutputMarkupId(true);
		
		final Label selectedDate = new Label("selectedDate", "至"+currDateStr+" 项目工时统计");
		selectedDate.setMarkupId("selectedDate").setOutputMarkupId(true);;

		final Form f = new Form("thisForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
				final ValueMap values = (ValueMap)getModelObject();
				
				
				
			}
		};

		
		add(selectedDate);
		
		final ModalWindow userDetailDlg = new ModalWindow("userDetailDlg");
		userDetailDlg.setTitle("个人项目工时明细");
		userDetailDlg.setCookieName("PERSON_PROJ_HOUR_COST_DIALOG");
		userDetailDlg.setInitialWidth(400);
		userDetailDlg.setInitialHeight(400);
		userDetailDlg.setWidthUnit("px");
		userDetailDlg.setHeightUnit("px");
		userDetailDlg.setCloseButtonCallback(new ModalWindow.CloseButtonCallback()	{
			public boolean onCloseButtonClicked(AjaxRequestTarget target) {
				return true;
			}
		});
		add(userDetailDlg);
		
		final WebMarkupContainer projStatListPanel = new WebMarkupContainer("projStatListPanel");
		projStatListPanel.setOutputMarkupId(true);
		projStatListPanel.add(new ListView("projList", projStatList) {
			protected void populateItem(final ListItem item) {
				
				final Map row = (Map)item.getModel().getObject();
				
				item.add(new Label("beginDate", new PropertyModel(item.getModel(), "BEGIN_DATE")));
				item.add(new Label("allCost", new Model<String>(UtilsMisc.transHour(new PropertyModel(item.getModel(), "HOUR_COST").getObject()))));
				item.add(new Label("budgetHour", new Model<String>(new PropertyModel(item.getModel(), "BUDGET_HOUR").getObject().toString())));
				
				Label projIdx = new Label("projectIdx", (item.getIndex()+1)+"");
				item.add(projIdx);
				Label mileLabel = new Label("milestone", new Model<String>((row.get("CURR_MILESTONE")==null?"":row.get("CURR_MILESTONE"))+"阶段"));
				item.add(mileLabel);
				Label deptLabel = new Label("dept", new PropertyModel(item.getModel(), "DEPT_NAME"));
				item.add(deptLabel);
				
				if(StringUtils.isEmpty((String)row.get("FATHER_PROID"))) {
					item.add(new ExternalLink("projectName", new PropertyModel(item.getModel(), "TASK_ADDR"), new PropertyModel(item.getModel(), "PROJ_NAME")));
				}
				else {
					item.add(new ExternalLink("projectName", null, "[子项目]"+row.get("PROJ_NAME")));
					deptLabel.setDefaultModel(new Model<String>("属于["+getMainService().getProjName((String)row.get("FATHER_PROID"))+"]"));
					
					mileLabel.setVisible(false);
				}
				
				
				final StringBuffer criteria = new StringBuffer("(u.project_id = '"+new PropertyModel(item.getModel(), "PROJECT_ID").getObject()+"'");
				criteria.append(" or u.project_id in (select project_id from project where father_proid = '"+new PropertyModel(item.getModel(), "PROJECT_ID").getObject()+"'))");
				String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
				String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
				
				if(StringUtils.isNotBlank(beginDateStr)) {
					criteria.append(" and u.reg_date >= '"+beginDateStr+"'");
				}
				if(StringUtils.isNotBlank(endDateStr)) {
					criteria.append(" and u.reg_date <= '"+endDateStr+"'");
				}
				
				Map paramMap = UtilsMisc.toMap("criteria", criteria.toString());
				String sql = ExpressionUtil.parse(getMainService().getProjUserCostSql(), paramMap);
				
				final WebMarkupContainer userProjDetail = new WebMarkupContainer("userProjDetail");
				userProjDetail.setOutputMarkupId(true);
				
				userProjDetail.add(new ListView("userProjCost", getMainService().getJdbcTemplate().queryForList(sql)) {

					@Override
					protected void populateItem(final ListItem detailItem) {
						detailItem.add(new AjaxLink("userProjCostLink"){

							@Override
							public void onClick(AjaxRequestTarget target) {
								userDetailDlg.setTitle(new PropertyModel(detailItem.getModel(), "NAME").getObject() + "在[" +new PropertyModel(item.getModel(), "PROJ_NAME").getObject()+ "]项目的工时明细");
								userDetailDlg.setContent(new UserProjCostPanel(userDetailDlg.getContentId(), getMainService().getJdbcTemplate(), criteria.toString() + " and u.user_id = '"+new PropertyModel(detailItem.getModel(), "USER_ID").getObject()+"'"));
								userDetailDlg.show(target);
							}
							
						}.add(new Label("userProjCostName", new PropertyModel(detailItem.getModel(), "NAME").getObject()+"("+UtilsMisc.transHour(new PropertyModel(detailItem.getModel(), "HOUR_COST").getObject())+"天)")));
					}
				});
				
				item.add(userProjDetail);
			}
			
		});
		add(projStatListPanel);
		
		f.add(feedbackPanel);
		
		f.add(beginDate);
		f.add(endDate);
		
		final DeptProjMultiChoice projs = new DeptProjMultiChoice("projs", 6);
		projs.setMarkupId("projs");
		projs.setOutputMarkupId(true);
		projs.init(getMainService().getDeptAndProjs(getUser(), false));
//		projs.getProjs(getMainService().getJdbcTemplate(), getUser());
		

		f.add(new AjaxSubmitButton("statButt") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				projStatList.clear();	
				String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
				String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
				
				String projId = projs.getModelValue();
				
				if(StringUtils.isNotBlank(projId) && !"-1".equals(projId)) {
					
					String[] projsArr = projId.split("\\;");
					List<String> projIdList = new ArrayList<String>();
					for (int i = 0; i < projsArr.length; i++) {
						//第一个字符为P或D，去除
						//这里主要考虑本人负责的项目和部门项目重复的情况，去重
						if(!projIdList.contains(projsArr[i].substring(1))) {
							projIdList.add(projsArr[i].substring(1));
						}
					}

					String criteria = "p.project_id in ('"+StringUtils.join(projIdList.toArray(), "','")+"')";
					
					String uhcriteria = "1=1";
					if(StringUtils.isNotBlank(beginDateStr)) {
						uhcriteria += " and u.reg_date >= '"+beginDateStr+"'";
					}
					if(StringUtils.isNotBlank(endDateStr)) {
						uhcriteria += " and u.reg_date <= '"+endDateStr+"'";
					}
					
					Map paramMap = UtilsMisc.toMap("uh_criteria", uhcriteria.toString(), "criteria", criteria);

					String sql = ExpressionUtil.parse(getMainService().getProjCostStatSql(), paramMap);
					//主项目统计
					List mainProjStatList = getMainService().getJdbcTemplate().queryForList(sql);

					//统计子项目，然后根据father_proid合并到主项目中去
					criteria = "p.father_proid in ('"+StringUtils.join(projsArr, "','")+"')";
					paramMap = UtilsMisc.toMap("uh_criteria", uhcriteria.toString(), "criteria", criteria);
					sql = ExpressionUtil.parse(getMainService().getProjCostStatSql(), paramMap);
					List subProjStatList = getMainService().getJdbcTemplate().queryForList(sql);
					
					for (Iterator iterator = mainProjStatList.iterator(); iterator.hasNext();) {
						Map mainProjStat = (Map) iterator.next();
						BigDecimal mHourCost = (BigDecimal)mainProjStat.get("HOUR_COST");
						
						for (Iterator iterator2 = subProjStatList.iterator(); iterator2.hasNext();) {
							Map subProjStat = (Map) iterator2.next();
							if(subProjStat.get("FATHER_PROID").equals(mainProjStat.get("PROJECT_ID"))) {
								if(subProjStat.get("HOUR_COST") != null)
									mHourCost = mHourCost.add((BigDecimal)subProjStat.get("HOUR_COST"));
							}
						}
						
						mainProjStat.put("HOUR_COST", mHourCost);
					}
					
					projStatList.addAll(mainProjStatList);
				}
				selectedDate.setDefaultModelObject("" + beginDateStr +"至"+endDateStr+" 项目工时统计");
				
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
			}
			
		});
		f.add(new AjaxSubmitButton("clearStatButt"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				projStatList.clear();	
			
				String beginDateStr = beginDate.getModelObject() == null ? "" : (String)beginDate.getModelObject();
				String endDateStr = endDate.getModelObject() == null ? "" : (String)endDate.getModelObject();
				selectedDate.setDefaultModelObject(beginDateStr +"至"+endDateStr+" 项目工时统计");
				
				target.addComponent(projStatListPanel);
				target.addComponent(selectedDate);
			}
			
		});
		
        f.add(projs);
		add(f);
		
	}
	
}
